package com.ruixin.parser;

import com.ruixin.annotation.Parser;
import com.ruixin.annotation.Value;
import com.ruixin.base.BaseParser;
import com.ruixin.base.exception.BaseException;
import com.ruixin.base.util.BeanUtil;
import com.ruixin.config.ApplicationContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * value注解解释
 */
@Parser(annotation = Value.class)
public class ValueParser extends BaseParser<ApplicationContext> {

    public ValueParser(ApplicationContext context, Class<? extends Annotation> type) {
        super(context, type);
    }

    @Override
    public void parseField(Object bean, Field field) throws BaseException {
        super.parseField(bean, field);
        Value annotation = BeanUtil.getAnnotation(field, Value.class);
        String value = annotation.value();
        String regex = "\\$\\{(.*?)}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        if(matcher.find()){
            String group = matcher.group(1);
            String defaultValue = "";
            if(group.contains(":")){
                String[] strings = group.split(":");
                defaultValue = strings[1];
                value = strings[0];
            }
            String property = this.context.getEnvironment().getProperty(value, defaultValue);
            BeanUtil.invokeField(bean,field,property);
        }else{
            throw new BaseException("@Value注解解析异常，无法解析"+value);
        }
    }


}
